package com.j256.ormlite.hmos.apptools;

import com.j256.ormlite.logger.Logger;
import com.j256.ormlite.logger.LoggerFactory;
import com.j256.ormlite.support.ConnectionSource;
import ohos.aafwk.ability.AbilitySlice;

import ohos.aafwk.content.Intent;
import ohos.app.Context;

/**
 * OrmLiteAbilitySlice
 *
 */
public abstract class OrmLiteAbilitySlice<H extends OrmLiteRdbOpenHelper> extends AbilitySlice {
    private static Logger logger = LoggerFactory.getLogger(OrmLiteBaseAbility.class);
    private volatile H helper;
    private volatile boolean isCreated = false;
    private volatile boolean isDestroyed = false;

    /**
     * getHelper
     *
     * @return helper
     */
    public H getHelper() {
        if (helper == null) {
            if (!isCreated) {
                throw new IllegalStateException("A call has not been made to onCreate() yet so the helper is null");
            } else if (isDestroyed) {
                throw new IllegalStateException(
                        "A call to onDestroy has already been made and the helper cannot be used after that point");
            } else {
                throw new IllegalStateException("Helper is null for some unknown reason");
            }
        } else {
            return helper;
        }
    }

    /**
     * ConnectionSource
     *
     * @return helper
     */
    public ConnectionSource getConnectionSource() {
        return getHelper().getConnectionSource();
    }

    /**
     * getRdbOpenHelperClass
     *
     * @return class
     */
    public abstract Class getRdbOpenHelperClass();

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        if (helper == null) {
            helper = getHelperInternal(this);
            isCreated = true;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        releaseHelper(helper);
        isDestroyed = true;
    }

    /**
     * getHelperInternal
     *
     * @param icontext Context
     * @return newHelper
     */
    protected H getHelperInternal(Context icontext) {
        @SuppressWarnings({"unchecked"})

        H newHelper = (H) OpenHelperManager.getHelper(icontext, getRdbOpenHelperClass());
        logger.trace("{}: got new helper {} from OpenHelperManager", this, newHelper);
        return newHelper;
    }

    /**
     * releaseHelper
     *
     * @param helper Helper
     */
    protected void releaseHelper(H helper) {
        OpenHelperManager.releaseHelper();
        logger.trace("{}: helper {} was released, set to null", this, helper);
        this.helper = null;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "@" + Integer.toHexString(super.hashCode());
    }
}
